package com.xiaoyun.lzg.controller;

import cn.hutool.core.util.StrUtil;
import com.xiaoyun.lzg.strategy.SuffixManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.any23.encoding.TikaEncodingDetector;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class FreeMarkerController {


    @Autowired
    FreeMarkerUtil freeMarkerUtil;

    @Autowired
    SuffixManager suffixManager;

    @PostMapping("read")
    public List<String> read(MultipartFile file) throws IOException {
        //BufferedInputStream支持mark，可以重复读取stream，避免网络请求2次
        BufferedInputStream is = new BufferedInputStream(file.getInputStream());

        is.mark(1000000);//10M
        //第一次处理stream，得到encoding
        String encoding = new TikaEncodingDetector().guessEncoding(is);
        is.reset();
        List<String> strings = IOUtils.readLines(is, encoding);
        log.info("read:{}", strings);
        return strings;
    }


    /**
     * 生成代码接口
     *
     * @para tableName 表名
     * @para saveUrl 生成文件路径
     * @para basePackageUrl 生成上级包名
     */
    @PostMapping("getTable")
    public Object createEntity(MultipartFile file) {
        Map<String, Object> root = new HashMap<>();
        String fileOriginalFilename = file.getOriginalFilename();
        if (freeMarkerUtil.isBlank(fileOriginalFilename)) {
            return "文件不能为空";
        }
        String[] str = fileOriginalFilename.split("\\.");
        String suffix = str[str.length - 1];
        Object result = null;
        if (str.length == 2 && (StrUtil.endWithAny(suffix, "txt", "zip", "rar"))) {
            try (InputStream inputStream = file.getInputStream()) {
                result = suffixManager.manager(suffix, fileOriginalFilename, inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }


    @PostMapping("saveBean")
    public String saveBean(Map<String, Object> map) throws Exception {
        freeMarkerUtil.generate(map);
        return "ok";
    }

}
